package com.example.designpatterns.singleton;

/**
 * 单例模式
 */
public class Singleton {

    private Singleton(){}

    public static volatile Singleton singleton2 = null;

    private static final Singleton singleton = new Singleton();

    /**
     * 恶汉式
     * @return
     */
    public static Singleton getInstance(){
        return  singleton;
    }

    /**
     * 懒汉式
     * @return
     */
    public static Singleton getInstance2(){
        if(null == singleton2){
            singleton2 =  new Singleton();
        }
        return singleton2;
    }

    /**
     * 懒汉式-加锁
     * @return
     */
    public static synchronized Singleton getInstance3(){
        if(null == singleton2){
            singleton2 =  new Singleton();
        }
        return singleton2;
    }

    /**
     * 懒汉式-双重校验加锁
     * @return
     */
    public static Singleton getInstance4(){
        if(null == singleton2){
            synchronized (Singleton.class){
                if(null == singleton2) {
                    singleton2 = new Singleton();
                }
            }
        }
        return singleton2;
    }

    /**
     * 静态内部类
     */
    private static class LazyHoder{

        private static final Singleton lazyHoder = new Singleton();
    }

    /**
     * 静态内部类(恶汉式)
     * @return
     */
    public static Singleton getInstance5(){
        return  LazyHoder.lazyHoder;
    }


    public static Singleton getInstance6(){
        return EnumSingleton.INSTANCE.getInstance();
    }

    /**
     * 测试
     * @param args
     */
    public static void main(String[] args) {
        Singleton singleton = getInstance6();
        System.out.println(singleton);
    }
}
